package com.bluexmicro.android.upgradebox.screen.upgrade

import android.Manifest
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.widget.ScrollView
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.bluexmicro.android.upgradebox.KeepScreenOn
import com.bluexmicro.android.upgradebox.R
import com.bluexmicro.android.upgradebox.screen.file.getBinName
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberPermissionState
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.asStateFlow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UpgradeScreen(onBackCallback: () -> Unit) {
    val context = LocalContext.current
    val viewModel: UpgradeViewModel = viewModel()
    val ready = viewModel.allReady.collectAsState(true)

    DisposableEffect(Unit) {
        viewModel.loadLocalData(context)
        viewModel.launchProcess(context, 500)
        onDispose {
            viewModel.finishProcess()
        }
    }
    KeepScreenOn()
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("OTA升级", color = MaterialTheme.colorScheme.onPrimary) },
                navigationIcon = {
                    IconButton(onClick = {
                        //todo 进行中提示是否结束OTA
                        onBackCallback.invoke()
                    }) {
                        Icon(
                            painter = painterResource(id = R.drawable.ic_arrow_left),
                            null,
                            tint = MaterialTheme.colorScheme.onPrimary,
                            modifier = Modifier
                                .size(16.dp)
                                .defaultMinSize(minWidth = 0.dp, minHeight = 0.dp)
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.primary)
            )
        },

        ) {
        if (ready.value) {
            UpgradeView(it, viewModel)
        } else {
            PremiseView(it, viewModel)
        }
    }
}


@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun PremiseView(paddingValues: PaddingValues, viewModel: UpgradeViewModel) {

    val bluetoothEnable = viewModel.bluetoothEnable.collectAsState()

    val bluetoothScan = viewModel.scanPermission.collectAsState()

    val bluetoothConnect = viewModel.connectPermission.collectAsState()

    val locationEnable =
        viewModel.locationEnable.collectAsState()

    val localPermission =
        viewModel.locationPermission.collectAsState()

    val context = LocalContext.current
    val scanPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        rememberPermissionState(Manifest.permission.BLUETOOTH_SCAN)
    } else {
        null
    }
    val connectPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        rememberPermissionState(Manifest.permission.BLUETOOTH_CONNECT)
    } else {
        null
    }
    val locationPermission = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION)
    val locationSetting =
        rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        }

    Column(
        modifier = Modifier
            .padding(paddingValues)
            .fillMaxWidth()
            .padding(top = 16.dp, start = 16.dp, end = 16.dp, bottom = 8.dp)
    ) {
        Text("当前蓝牙不可用", style = MaterialTheme.typography.titleMedium)
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            "可能是未授权APP使用蓝牙相关的权限或者功能异常，请根据下面提示提示授于app权限和检查必要的功能",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.5f)
        )
        Divider(thickness = Dp.Hairline, modifier = Modifier.padding(vertical = 16.dp))

        ConditionItem("蓝牙开关", "打开", bluetoothEnable.value.not()) {
            viewModel.enableBluetooth(context)
        }
        Spacer(modifier = Modifier.height(16.dp))
        ConditionItem("蓝牙扫描权限", "授权", bluetoothScan.value.not()) {
            scanPermission?.launchPermissionRequest()
        }
        Spacer(modifier = Modifier.height(16.dp))
        ConditionItem("蓝牙连接权限", "授权", bluetoothConnect.value.not()) {
            connectPermission?.launchPermissionRequest()
        }
        Spacer(modifier = Modifier.height(16.dp))
        ConditionItem("位置信息开关", "打开", locationEnable.value.not()) {
            locationSetting.launch(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
        }
        Spacer(modifier = Modifier.height(16.dp))
        ConditionItem("位置信息权限", "授权", localPermission.value.not()) {
            locationPermission.launchPermissionRequest()
        }
    }
}

@Composable
fun ConditionItem(
    content: String,
    buttonTxt: String,
    buttonEnable: Boolean,
    onTap: () -> Unit
) {
    Card {
        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp)) {
            Text(content, modifier = Modifier.weight(1f))
            OutlinedButton(onClick = onTap, enabled = buttonEnable) {
                Text(buttonTxt)
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////

@Composable
fun UpgradeView(paddingValues: PaddingValues, viewModel: UpgradeViewModel) {

    val currentTask = remember {
        viewModel.currentTask
    }

    val successList = remember {
        viewModel.successList
    }

    val failedList = remember {
        viewModel.failedList
    }

    Column(
        modifier = Modifier
            .padding(paddingValues)
            .padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 0.dp)
    ) {
        Card(
            modifier = Modifier.fillMaxWidth(),
        ) {
            if (currentTask.value == null) {
                Text(
                    "正在扫描...",
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(32.dp),
                    textAlign = TextAlign.Center
                )
            } else {
                CurrentTaskItem(currentTask.value!!)
            }
        }
        Spacer(modifier = Modifier.height(8.dp))
        LazyColumn {
            item {
                Spacer(modifier = Modifier.height(16.dp))
                Text("成功的设备")
                Divider(
                    thickness = Dp.Hairline,
                    modifier = Modifier.padding(top = 8.dp, bottom = 16.dp)
                )
            }

            itemsIndexed(successList) { index, item ->
                Text("${index + 1}. ${item.mac}")
            }

            item {
                Spacer(modifier = Modifier.height(16.dp))
                Text("失败的设备")
                Divider(
                    thickness = Dp.Hairline,
                    modifier = Modifier.padding(top = 8.dp, bottom = 16.dp)
                )
            }

            itemsIndexed(failedList) { index, item ->
                Text("$index. ${item.mac}")
            }

        }
    }
}

@Composable
fun CurrentTaskItem(record: UpgradeRecord) {
    Column(modifier = Modifier.padding(16.dp)) {
        Text("MAC: ${record.mac}")
        record.resInfoList.forEachIndexed { index, res ->
            TaskItem(index, res)
        }
    }
}

@Composable
fun TaskItem(index: Int, res: ResourceInfo) {
    val progress = remember {
        res.progress
    }
    Row(modifier = Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically) {
        Text(
            res.path.getBinName(),
            style = MaterialTheme.typography.bodySmall,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.weight(1f)
        )
        Text("    ${(progress.value * 100).toInt()}%")
    }
}

// todo 息屏、低电量
//@Composable
//fun SuccessItem(record: UpgradeRecord) {
//    Column {
//        Text("MAC: ${record.mac}")
//        record.resInfoList.forEachIndexed { index, res ->
//            TaskItem(index, res)
//        }
//    }
//}
//
//@Composable
//fun FailedItem(record: UpgradeRecord) {
//    // todo 失败次数
//}

/////////////////////////////////////////////////////////////////////////////
////
/////////////////////////////////////////////////////////////////////////////
//@Composable
//fun TaskItem(info: ResourceInfo) {
//    Column {
//        Text("${info.path.getBinName()}(${info.size})")
//        Text("Progress: ${(info.progress.value * 100).toInt()}%")
//        Text("耗时：${info.costTime}秒")
//        Divider(thickness = Dp.Hairline)
//    }
//}